package org.tnaggs.project.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.tnaggs.project.model.Player;

public class PlayerRepository implements GenericRepository<Player> {
	
	
	private JdbcTemplate template;
	
	public PlayerRepository(JdbcTemplate template) {
		this.setTemplate(template);
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	public List<Player> findAllByTeamID(long teamID) {
		return (List<Player>)template.query("select * from Player where team=" + teamID, new PlayerRowMapper());
	}
	
	@Override
	public Player findByID(int id) {
		return (Player)template.queryForObject("select * from Player where Player_ID = " + id, new PlayerRowMapper());
	}
	
	@Override
	public List<Player> findAll() {
		return (List<Player>)template.query("select * from Player", new PlayerRowMapper());
	}
	
	class PlayerRowMapper implements RowMapper<Player> {

		@Override
		public Player mapRow(ResultSet rs, int arg1) throws SQLException {
		
				Player results = new Player();
				results.setPlayerID(rs.getInt("Player_ID"));
				results.setContactID(rs.getInt("Contact"));
				results.setAge(rs.getInt("Age"));
				results.setPosition(rs.getString("Position"));
				results.setTeamID(rs.getInt("Team"));
				return results;
		}

		
		
	}


	@Override
	public boolean insert(Player newVal) {
		int numResults = template.update("insert into Player (`Age`, `Position`, `Contact`, `Team`) values("  
				+ newVal.getAge() + ",'" + newVal.getPosition() + "','" 
				+newVal.getContactID() + "',"
				+newVal.getTeamID() + ")");
		return numResults == 1;
	}

	@Override
	public boolean delete(int id) {
		int numResults =  template.update("delete from Player where Player_ID = " + id);
		return numResults == 1;
	}

	@Override
	public boolean purge() {
      int numResults = template.queryForInt("select count(*) from Player;");
      int delResults = template.update("delete from Player;");
      return numResults == delResults;
	}
}
